package com.huawei.crm.util;

import lombok.experimental.UtilityClass;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.DosFileAttributes;

/**
 * describe
 *
 * @author 罗华
 * @date 2024/10/16 14:20
 */
@UtilityClass
public class IOUtil {

    /**
     * 把内容写入到指定文件夹路径
     *
     * @param content
     * @param filePath
     */
    public void writeContent(String content, String filePath) {
        createDirectoryPath(filePath);
        try {
            Files.write(Paths.get(filePath), content.getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void createDirectoryPath(String directoryPath) {
        int lastIndexOf = directoryPath.lastIndexOf("/");
        Path directory = Paths.get(directoryPath.substring(0, lastIndexOf));
        try {
            if (!Files.exists(directory)) {
                Files.createDirectories(directory);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void setDirectoryWritable(Path directory, boolean writable) throws IOException {
        if (Files.isReadable(directory)) {
            // 获取当前的 DOS 属性
            DosFileAttributes attrs = Files.readAttributes(directory, DosFileAttributes.class);
            // 设置新的 DOS 属性
            Files.setAttribute(directory, "dos:readonly", !writable);

            System.out.println("Directory is now " + (writable ? "writable" : "read-only"));
        } else {
            System.err.println("Directory is not readable, cannot set attributes.");
        }
    }

    /**
     * 读取文件字符串内容
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    public String readToStr(String filePath) throws IOException {
        return new String(Files.readAllBytes(Paths.get(filePath)));
    }

    /**
     * 根据url读取内容
     *
     * @param url
     * @return
     */
    public String urlString(String url) {
        StringBuilder res = new StringBuilder();
        try {
            URL urls = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) urls.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                res.append(line);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("res:" + res);
        return res.toString();
    }

}
